package com.multitrack.map.datatype;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;

public class CustomMapView extends MapView {

	public interface OnLongPressListener {
		public void onLongPress(MapView mapView, GeoPoint longPressLocation);
	}

	static final int LONGPRESS_THRESHOLD = 500;

	private GeoPoint lastMapCenter;
	private GeoPoint longPressLocation;
	private Timer longPressTimer = new Timer();
	private CustomMapView.OnLongPressListener longPressListener;

	public CustomMapView(Context context, String apiKey) {
		super(context, apiKey);
	}

	public CustomMapView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public CustomMapView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);

	}

	public void setOnLongPressListener(
			CustomMapView.OnLongPressListener listener) {
		longPressListener = listener;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		handleLongPress(event);
		return super.onTouchEvent(event);
	}

	private void handleLongPress(final MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {

			longPressTimer = new Timer();
			longPressTimer.schedule(new TimerTask() {

				public void run() {
					longPressLocation = getProjection().fromPixels(
							(int) event.getX(), (int) event.getY());

					longPressListener.onLongPress(CustomMapView.this,
							longPressLocation);
				}
			}, LONGPRESS_THRESHOLD);

			lastMapCenter = getMapCenter();

		}
		if (event.getAction() == MotionEvent.ACTION_MOVE) {

			if (!getMapCenter().equals(lastMapCenter)) {
				longPressTimer.cancel();
			}
			lastMapCenter = getMapCenter();
		}

		if (event.getAction() == MotionEvent.ACTION_UP) {
			longPressTimer.cancel();
		}

		if (event.getPointerCount() > 1) {
			longPressTimer.cancel();
		}

	}

	public GeoPoint getLongPressLocation() {
		return longPressLocation;
	}
}